package io.gitee.hefren.hhregistry.health;

import io.gitee.hefren.hhregistry.beans.InstanceMeta;
import io.gitee.hefren.hhregistry.service.RegisterService;
import io.gitee.hefren.hhregistry.service.impl.HhRegisterService;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @Date 2024/5/13
 * @Author lifei
 */
public class HhCheckHealth implements CheckHealth{

    private static final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();

    private final long timeout = 30 * 1000;

    private final RegisterService registerService;

    public HhCheckHealth(RegisterService registerService) {
        this.registerService = registerService;
    }

    @Override
    public void start() {
        executor.scheduleWithFixedDelay(()->{
            for (String serverAndInstance : HhRegisterService.TIMESTEMPS.keySet()) {
                if (HhRegisterService.TIMESTEMPS.get(serverAndInstance) - System.currentTimeMillis() > timeout) {
                    int index = serverAndInstance.indexOf("@");
                    String server  = serverAndInstance.substring(0, index);
                    String url = serverAndInstance.substring(index + 1);
                    InstanceMeta instanceMeta = InstanceMeta.fromUrl(url);
                    registerService.unregister(server, instanceMeta);
                    HhRegisterService.TIMESTEMPS.remove(serverAndInstance);
                }
            }
        }, 10, 10, TimeUnit.SECONDS);
    }

    @Override
    public void stop() {
        executor.shutdown();
    }
}
